<?php

namespace App\Kuafu\ProductMenu\Controller\Applet;

use App\Kuafu\Base\Enum\ClientEnum;
use App\Kuafu\Category\Service\CategoryService;
use App\Kuafu\ProductMenu\Service\ProductMenuService;
use App\Kuafu\Shop\Enum\CodeEnum;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Service\ShopAppletService;
use App\Kuafu\Shop\Service\ShopService;
use Illuminate\Http\Request;
use App\Kuafu\Base\Controller\BaseController;

class ProductMenuController extends BaseController
{
    /**
     * 店铺的菜品、分类列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\Shop\Exceptions\ShopException
     */
    public function shopMenu(Request $request)
    {
        $shopId = (int)$request->header('shopId');
        $appid  = (string)$request->header('appid');

        if ((empty($appid) || $appid == CodeEnum::SHOP_OLD_APPLE_ID) && ShopAppletService::checkIsNew($shopId)) {
            return $this->fail(ShopCodeEnum::SHOP_APPID_NOT_RIGHT,
                ShopCodeEnum::CODE_TEXT[ShopCodeEnum::SHOP_APPID_NOT_RIGHT]);
        }

        // 店铺的菜单信息
        $shop = ShopService::getShopInfo($shopId);
        if (!$shop) {
            return $this->fail(ShopCodeEnum::ERR_SHOP_ID_NO_EXIST);
        }

        $brandId = $shop->brandId;
        $menuId  = $shop->menuId;
        if (!$menuId) {
            throw new ShopException(ShopCodeEnum::ERR_SHOP_NO_MENU);
        }
        // 菜品列表
        $oriList     = ProductMenuService::shopProductLists(ClientEnum::CLIENT_PRODUCT_APPLET);
        $productList = [];

        // 分类信息
        $field        = ['id', 'name', 'sort'];
        $data         = CategoryService::filterNoProductCategory($brandId, $menuId, $field, $oriList,
            $productList, 1);
        $productList  = $data['productList'];
        $categoryList = $data['categoryList'];


        $data = [
            'productList'  => $productList,
            'categoryList' => $categoryList,
        ];

        return $this->success($data);
    }
}
